#!/usr/bin/python
# -*- coding:utf-8 -*-
#scriptName OF3D_zchPipePublicClass.py
#
#import OF3D_PublicClass.OF3D_zchPipePublicClass as OF3D_zchPipePublicClass
#class SkinWeightImExport(OF3D_zchPipePublicClass.PublicClass):
import maya.cmds as mc
import maya.mel as mel
import maya.OpenMaya as OpenMaya
import time
import sys,re,os
import tools_Persional.LZ_Tools.LZ_Tools.OF3D_PublicClass.mayaPrint as mayaPrint

class Naming( mayaPrint.MayaPrint ):
    def __init__(self):
        mayaPrint.MayaPrint.__init__(self)
        #self.allObjects = []
    def getLastName(self,name):
        if("|" in name):
            name = re.split("\|",name)[-1]
        return name
    def dealPrefix(self,objectName,prefix,newPrefix):
        Result = None
        objectName = re.sub('\n','',objectName)
        if(prefix == '+'):                      #prefix add mode
            if("|" in objectName):
                nameSplit = objectName.split("|")
                nameSplitList = ['%s%s'%(newPrefix,x) for x in nameSplit]
                nslCount = len(nameSplitList)
                for i,x in enumerate(nameSplitList):
                    if i != (nslCount-1):
                        Result = x+'|'
                    else:
                        Result += x
            else:
                Result = '%s%s'%(newPrefix,objectName)
        #----prefix subtract mode----
        elif(prefix == '-'):
            if("|" in objectName):
                nameSplit = objectName.split("|")
                nameSplitList = ['%s'%(re.sub('^%s'%(newPrefix),'',x)) for x in nameSplit]
                nslCount = len(nameSplitList)
                for i,x in enumerate(nameSplitList):
                    if i != (nslCount-1):
                        Result = x+'|'
                    else:
                        Result += x
            else:
                Result = re.sub('^%s'%(newPrefix),'',objectName)
        #----prefix replace mode----
        elif(type(prefix) == str and prefix != '' and prefix != None):
            if("|" in objectName):
                nameSplit = objectName.split("|")
                nameSplitList = ['%s'%(re.sub('^%s'%(prefix),newPrefix,x)) for x in nameSplit]
                nslCount = len(nameSplitList)
                for i,x in enumerate(nameSplitList):
                    if i != (nslCount-1):
                        Result = x+'|'
                    else:
                        Result += x
            else:
                Result = re.sub('^%s'%(prefix),newPrefix,objectName)
        else:
            self.mayaError('NOT <str> type argument')
        return Result
    def dealSuffix(self,objectName,suffix,newSuffix):
        Result = None
        objectName = re.sub('\n','',objectName)
        if(suffix == '+'):                      #suffix add mode
            if("|" in objectName):
                nameSplit = objectName.split("|")
                nameSplitList = ['%s%s'%(x,newSuffix) for x in nameSplit]
                nslCount = len(nameSplitList)
                for i,x in enumerate(nameSplitList):
                    if i != (nslCount-1):
                        Result = x+'|'
                    else:
                        Result += x
            else:
                Result = '%s%s'%(objectName,newSuffix)
        elif(suffix == '-'):                    #suffix subtract mode
            if("|" in objectName):
                nameSplit = objectName.split("|")
                nameSplitList = ['%s'%(re.sub('%s$'%(newSuffix),'',x)) for x in nameSplit]
                nslCount = len(nameSplitList)
                for i,x in enumerate(nameSplitList):
                    if i != (nslCount-1):
                        Result = x+'|'
                    else:
                        Result += x
            else:
                Result = re.sub('%s$'%(newSuffix),'',objectName)
        elif(type(suffix) == str and suffix != '' and suffix != None):                 #suffix replace mode
            if("|" in objectName):
                nameSplit = objectName.split("|")
                nameSplitList = ['%s'%(re.sub('%s$'%(suffix),newSuffix,x)) for x in nameSplit]
                nslCount = len(nameSplitList)
                for i,x in enumerate(nameSplitList):
                    if i != (nslCount-1):
                        Result = x+'|'
                    else:
                        Result += x
            else:
                Result = re.sub('%s$'%(suffix),newSuffix,objectName)
        else:
            self.mayaError('NOT <str> type argument')
        return Result
    def renameIkEff(self,ikHandleNm):
        effector = mc.listConnections((ikHandleNm+".endEffector"))
        newName = ikHandleNm.replace("_ikh","_eff")
        mc.rename(effector[0],newName)
        mc.select(cl=True)
        return newName
    #the top object at the end of list
    def getAllObjs(self,inputName=None,_Type=[],skipGrp=[],end=None):
        """
        """
        if inputName==None:
            objList = mc.ls(sl=True)
            if len(objList)!=1 or objList==None:
                self.mayaWarning("No 1 object selected !")
                return None
        else:
            if mc.objExists(inputName)==0:
                self.mayaWarning("No object %s."%(inputName))
                return None
            objList = [inputName]
        allDescendents = []
        parentObj = mc.listRelatives(objList[0],fullPath=True,p=True)
        if parentObj==None:
            roof = objList[0]
        elif parentObj!=None:
            bufferList = re.split("\|",parentObj[0])
            roof = bufferList[1]
        self.allObjects = []
        self.__getChildrens(roof,type=_Type,skipGrp=skipGrp,end=end)
        self.allObjects.append(roof)
        return self.allObjects
    #getAllChildren(self,roof,_Type=[],skipGrp=[],end=None):
    def getAllChildren(self,roof,**flags):
        """
        get children's children ...
        """
        self.allObjects = []
        self.__getChildrens(roof,**flags)
        return self.allObjects
    #get children's children ...
    def __getChildrens(self,roof,**flags):
        """
        get children's children ...
        """
        defineFlags = {"type":([],list,"",str,u'',unicode) ,"skipGrp":([],list,'',str) ,"end":('',str,u'',unicode,None,None),"shapes":(True,bool)}
        flagDirect = self.funtionFlag(defineFlags,**flags)
        ##read from flagDirect
        _Type = flagDirect[ "type" ]
        skipGrp = flagDirect[ "skipGrp" ]
        end = flagDirect[ "end" ]
        shapes = flagDirect[ "shapes" ]
        #make skipGrp is list
        if type(skipGrp)==str or type(skipGrp)==unicode:
            skipGrp = [skipGrp]
        #make type is list
        if type(_Type)==str or type(_Type)==unicode:
            _Type = [_Type]
        #list its children
        #chidren = mc.listRelatives(roof,children=True,type=_Type,pa=True)
        chidren = mc.listRelatives(roof,children=True,pa=True)
        #include shape ?
        itsShapes = mc.listRelatives(roof,pa=True,shapes=True)
        if shapes==False and itsShapes!=None:
            for sap in itsShapes:
                try:
                    chidren.remove( sap )
                except:
                    pass
        #if chidren!=None:
        if chidren!=None:
            for c in chidren:
                #weather add the object
                addIt =True
                getNext = True
                #check is a skip group?
                for x in skipGrp:
                    if re.search("%s$"%(x),c)!=None:
                        addIt = False
                        getNext = False
                #check is a need type?
                if addIt and len(_Type)>0:
                    addIt = False
                    for typ in _Type:
                        if mc.objectType(c)==typ:
                            addIt = True
                            break
                #add object name in list
                if addIt:
                    self.allObjects.append(c)
                if c==end:
                    break
                if getNext:
                    self.__getChildrens(c,**flags)
        return self.allObjects
        
    def find_AllCtrls(self):
        """
        find all sets wiht suffix AllCtrls or Allctrls
        #from:
        method in OF3D_PublicClass/objectName.py/
        """
        resList = []
        allSets = mc.ls(type="objectSet")
        for aset in allSets:
            if re.search("AllCtrls$|Allctrls$",aset)!=None:
                resList.append( aset )
        return resList
        
    def getSetMembers(self,aSet,resList=[]):
        """Returns all the children, grand-children etc.
        #from:
        method in OF3D_PublicClass/objectName.py/
        """
        if mc.objExists(aSet):
            members = mc.sets(aSet,q=True)
            for mem in members:
                    if mc.objectType(mem,isAType="objectSet"):
                        self.getSetMembers(mem,resList)
                    else:
                        resList.append( mem )
                    
    def checkRepeatName(self):
        """
        """
        print "can replace method by qualityAssurance.qa_hasRepeatName"
        allObjs= self.getAllObjs()
        if allObjs==None:
            self.mayaWarning("Please select 1 object.")
            return
        hasProb = False
        for x in allObjs:
            lsThObj = mc.ls(x)
            if len(lsThObj)>1 or "|" in x:
                self.mayaWarning("Repeat Name: %s."%(x),True)
        if hasProb==False:
            self.mayaPrint("Well Done.")
            return True
        else:
            return False
            
#instance
NamingCls = Naming()